package com.mengma.ec.service.impl.portal;

import com.mengma.ec.commons.Const;
import com.mengma.ec.commons.ResponseCode;
import com.mengma.ec.commons.ServerResponse;
import com.mengma.ec.dao.UserMapper;
import com.mengma.ec.entity.User;
import com.mengma.ec.service.portal.IUserService;
import com.mengma.ec.util.MD5Util;
import com.mengma.ec.util.RedisComponent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Tangzhiqiang
 * @Date: 2018/9/12 0012 14:38
 * @Description: 类描述！！！！
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisComponent redisComponent;

    /**
     * 检查用户名是否存在
     *
     * @param user
     * @return
     */
    @Override
    public ServerResponse<User> login(User user) {

        ServerResponse response_username = check_valid(user.getUsername(), Const.USERNAME);

        //用户名不存在
        // 判断用户名是否存在 —— 提示用户名是否
        if (response_username.isSuccess()) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "用户不存在");

        }

        // 通过用户名与密码查询数据库进行判断是否正确 —— 提示用户名或密码错误
        String md5Password = MD5Util.MD5EncodeUtf8(user.getPassword());

        User currentUser = userMapper.loginByUserNameAndPd(user.getUsername(), md5Password);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "用户名或密码错误!");
        }
        return ServerResponse.createBySuccess("恭喜您登录成功了！", currentUser);
    }

    @Override
    public ServerResponse<User> register(User user) {


        ServerResponse response_username = check_valid(user.getUsername(), Const.USERNAME);

        //用户名不存在
        // 判断用户名是否存在 —— 提示用户名是否
        if (!response_username.isSuccess()) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "用户已存在");

        }

        ServerResponse response_email = check_valid(user.getEmail(), Const.EMAIL);
        if (!response_email.isSuccess()) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "邮箱已存在");

        }

        //密码MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        //设置当前用户角色
        user.setRole(Const.Role.ROLE_CUSTOMER);

        int i = userMapper.insert(user);
        if (i == 0) {
            return ServerResponse.createByErrorCodeMessage(444, "当前系统繁忙，请稍后再试！");
        }
        return ServerResponse.createByErrorCodeMessage(444, "注册成功！");
    }


    /**
     *
     */
    @Override
    public ServerResponse check_valid(String str, String type) {

        //首先进行 用户名判断
        if (Const.USERNAME.equals(type)) {
            int userName_count = userMapper.checkUserName(str);
            //存在
            if (userName_count > 0) {
                return ServerResponse.createByErrorMessage("用户名已存在！");
            }
        }

        //判断是不是email
        if (Const.EMAIL.equals(type)) {
            int i = userMapper.checkUserEmail(str);
            if (i > 0) {
                return ServerResponse.createByErrorMessage("email已存在！");
            }
        }
        // 成功就代表 用户名 Email不存在
        return ServerResponse.createBySuccessMessage("效验成功");
    }

    @Override
    public String forget_get_question(String username) {
        String question = userMapper.findQuestionByUserName(username);
        return question;
    }

    @Override
    public ServerResponse<String> forget_get_answer(String username, String question, String answer) {
        int count = userMapper.forget_get_answer(username, question, answer);

        //代表验证通过，需要返回Token给调用者
        if (count > 0) {
            //通过UUID生成简单并唯一的token
            String token = UUID.randomUUID().toString();

            //使用redis做数据缓存，用来缓存token （测试时间1分钟，方便测试）
            try {
                redisComponent.put(Const.TOKEN_PREFIX + username, token, 1, TimeUnit.MINUTES);
                return ServerResponse.createBySuccess(token);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ServerResponse.createByErrorMessage("问题答案回答错误！");
    }

    //    登录中状态重置密码
    @Override
    public ServerResponse<String> reset_password(String passwordOld, String passwordNew, HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);

        passwordOld = MD5Util.MD5EncodeUtf8(passwordOld);
        passwordNew = MD5Util.MD5EncodeUtf8(passwordNew);
        int i = userMapper.reset_password(passwordOld, passwordNew, user.getUsername());


        if (i > 0) {
            return ServerResponse.createBySuccess("重置密码成功！");
        }
        return ServerResponse.createByErrorMessage("重置密码失败！");
    }

    //    忘记密码的重设密码
    @Override
    public ServerResponse<String> forget_get_password(String username, String passwordNew, String token) {
        //验证用户名是否有效
        ServerResponse response = check_valid(username, Const.USERNAME);
        if (response.isSuccess()) {
            return ServerResponse.createByErrorMessage("当前用户不存在");
        }
        try {
            String auth_token = redisComponent.get(Const.TOKEN_PREFIX + username);
            //如果获取的认证token为空，代表token失效
            if (StringUtils.isBlank(auth_token)) {
                return ServerResponse.createByErrorMessage("token过时，请重新认证问题答案");
            }

            //验证用户token是否有效
            if (auth_token.equals(token)) {
                String md5 = MD5Util.MD5EncodeUtf8(passwordNew);
                int i = userMapper.updataPasswordByUserName(username, md5);
                if (i > 0) {
                    return ServerResponse.createBySuccess("修改成功！");
                }
                return ServerResponse.createByErrorMessage("当前系统繁忙，请稍后再试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMessage("当前系统繁忙!");
    }

    //    登录状态更新个人信息
    @Override
    public ServerResponse<User> updata_information(User user, HttpSession session) {
        // 第一步：需要知道是谁
        User current_user = (User) session.getAttribute(Const.CURRENT_USER);
        String username = current_user.getUsername();
        user.setUsername(username);
        int i =  userMapper.updata_information(user);
        if (i>0){
            return ServerResponse.createBySuccessMessage("更新成功!");
        }
        return ServerResponse.createByErrorMessage("更新失败!");
    }

    @Override
    public ServerResponse<User> get_information(User user) {
        User info_user= userMapper.selectByPrimaryKey(user.getId());

        if (info_user == null){
            return ServerResponse.createByErrorMessage("用户信息获取失败");
        }

        return ServerResponse.createBySuccess("获取成功",info_user);
    }
}
